﻿package com.example.weibo;

import com.example.openapi.legacy.StatusesAPI;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private WeiboAuth mWeiboAuth;
	private Button authButton;
	private Button shareButton;

	/** 当前 DEMO 应用的 APP_KEY，第三方应用应该使用自己的 APP_KEY 替换该 APP_KEY */
	public static final String APP_KEY = "3298204237";
	/**
	 * 当前 DEMO 应用的回调页，第三方应用可以使用自己的回调页。
	 * 建议使用默认回调页：https://api.weibo.com/oauth2/default.html
	 */
	public static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
	/**
	 * WeiboSDKDemo 应用对应的权限，第三方开发者一般不需要这么多，可直接设置成空即可。 详情请查看 Demo 中对应的注释。
	 */
	public static final String SCOPE = "email,direct_messages_read,direct_messages_write,"
			+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
			+ "follow_app_official_microblog," + "invitation_write";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		authButton = (Button) findViewById(R.id.btn1);
		shareButton = (Button) findViewById(R.id.btn2);
		authButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mWeiboAuth = new WeiboAuth(MainActivity.this, APP_KEY,
						REDIRECT_URL, SCOPE);
				mWeiboAuth.anthorize(authlistener);
			}
		});

		shareButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Oauth2AccessToken token = AccessTokenKeeper
						.readAccessToken(MainActivity.this);
				StatusesAPI api = new StatusesAPI(token);
				api.update("测试内容", "0.00", "0.00", new RequestListener() {
					@Override
					public void onWeiboException(WeiboException arg0) {
					}

					@Override
					public void onComplete(String arg0) {
					}
				});
			}
		});
	}

	private WeiboAuthListener authlistener = new WeiboAuthListener() {
		@Override
		public void onCancel() {
		}

		@Override
		public void onComplete(Bundle arg0) {
			Oauth2AccessToken token = Oauth2AccessToken.parseAccessToken(arg0);
			if (token.isSessionValid()) {
				// 保存 Token 到 SharedPreferences
				AccessTokenKeeper.writeAccessToken(MainActivity.this, token);
			} else {
				// 当您注册的应用程序签名不正确时，就会收到 Code，请确保签名正确
				String code = arg0.getString("code", "");
			}
		}

		@Override
		public void onWeiboException(WeiboException arg0) {
		}

	};
}
